package com.zj.fx.controller.month;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zj.fx.common.base.BaseController;
import com.zj.fx.common.domain.AjaxResult;
import com.zj.fx.common.domain.ResultTable;
import com.zj.fx.model.custom.Tablepar;
import com.zj.fx.model.info.*;
import com.zj.fx.model.month.*;
import com.zj.fx.service.info.InfoProjectService;
import com.zj.fx.service.info.InfoSupplyService;
import com.zj.fx.service.info.InfoTargetStepService;
import com.zj.fx.service.info.InfoWeburlService;
import com.zj.fx.service.month.MonthAuditDtlService;
import com.zj.fx.service.month.MonthNecessaryService;
import com.zj.fx.service.month.MonthSupplytaskDtlService;
import com.zj.fx.service.month.MonthSupplytaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 月评价供电所填报任务表Controller
 *
 * @author SQL
 * @ClassName: MonthSupplytaskController
 * @date 2023-06-09 16:19:27
 */
@Api(value = "月评价供电所填报任务表")
@Controller
@RequestMapping("/MonthSupplytaskController")
public class MonthSupplytaskController extends BaseController {

    private String prefix = "month/monthSupplytask";
    private String prefixana = "month/monthAnalysis";

    @Autowired
    private MonthSupplytaskService monthSupplytaskService;

    @Autowired
    private MonthSupplytaskDtlService monthSupplytaskDtlService;

    @Autowired
    private InfoProjectService infoProjectService;

    @Autowired
    private MonthNecessaryService monthNecessaryService;

    @Autowired
    private MonthAuditDtlService monthAuditDtlService;

    @Autowired
    private InfoTargetStepService infoTargetStepService;

    @Autowired
    private InfoWeburlService infoWeburlService;

    @Autowired
    private InfoSupplyService infoSupplyService;

    /**
     * 月评价供电所填报任务表页面展示
     *
     * @param model
     * @return String
     * @author SQL
     */
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/view")
    @RequiresPermissions("gen:monthSupplytask:view")
    public String view(ModelMap model) {
        return prefix + "/list";
    }

    /**
     * list集合
     *
     * @param tablepar
     * @param
     * @return
     */
    //@Log(title = "月评价供电所填报任务表", action = "111")
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/list")
    @RequiresPermissions("gen:monthSupplytask:list")
    @ResponseBody
    public ResultTable list(Tablepar tablepar, MonthSupplytask monthSupplytask) {
        PageInfo<MonthSupplytask> page = monthSupplytaskService.list4self(tablepar, monthSupplytask);
        return pageTable(page.getList(), page.getTotal());
    }

    /**
     * 新增跳转
     */
    @ApiOperation(value = "新增跳转", notes = "新增跳转")
    @GetMapping("/add")
    public String add(ModelMap modelMap) {
        return prefix + "/add";
    }

    /**
     * 新增保存
     *
     * @param
     * @return
     */
    //@Log(title = "月评价供电所填报任务表新增", action = "111")
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping("/add")
    @RequiresPermissions("gen:monthSupplytask:add")
    @ResponseBody
    public AjaxResult add(MonthSupplytask monthSupplytask) {
        int b = monthSupplytaskService.insertSelective(monthSupplytask);
        if (b > 0) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 月评价供电所填报任务表删除
     *
     * @param ids
     * @return
     */
    //@Log(title = "月评价供电所填报任务表删除", action = "111")
    @ApiOperation(value = "删除", notes = "删除")
    @DeleteMapping("/remove")
    @RequiresPermissions("gen:monthSupplytask:remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        int b = monthSupplytaskService.deleteByPrimaryKey(ids);
        if (b > 0) {
            return success();
        } else {
            return error();
        }
    }


    /**
     * 修改跳转
     *
     * @param id
     * @param
     * @return
     */
    @ApiOperation(value = "修改跳转", notes = "修改跳转")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap map) {
        map.put("MonthSupplytask", monthSupplytaskService.selectByPrimaryKey(id));

        return prefix + "/edit";
    }

    /**
     * 修改保存
     */
    //@Log(title = "月评价供电所填报任务表修改", action = "111")
    @ApiOperation(value = "修改保存", notes = "修改保存")
    @RequiresPermissions("gen:monthSupplytask:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MonthSupplytask monthSupplytask) {
        return toAjax(monthSupplytaskService.updateByPrimaryKeySelective(monthSupplytask));
    }

    /**
     * 填报页面跳转
     */
    @ApiOperation(value = "填报页面跳转", notes = "填报页面跳转")
    @GetMapping("/fill/{id}")
    public String fill(@PathVariable("id") String id, ModelMap modelMap) {
        //查询标签表头(一级+必备条件项目)
        List<InfoProject> infoProjects = infoProjectService.selectTabTitle();
        modelMap.put("tabTitleList", infoProjects);
        modelMap.put("taskId", id);
        return prefix + "/fill";
    }

    /**
     * 填报提报
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "填报提报", notes = "填报提报")
    @PostMapping("/fillCommit")
    @ResponseBody
    @Transactional
    public AjaxResult fillCommit(@RequestBody MonthSupplytask monthSupplytask) {
        //0、关键数据获取
        String id = monthSupplytask.getId();
        //------------1、数据校验、查询任务下子任务的数据填报规范性
        //1.1 查询是否有漏填项
        //1.1.1 必备项
        MonthNecessaryExample monthNecessaryExample = new MonthNecessaryExample();
        MonthNecessaryExample.Criteria criteria = monthNecessaryExample.createCriteria();
        criteria.andFkTaskIdEqualTo(id);
        List<MonthNecessary> monthNecessaries = monthNecessaryService.selectByExample(monthNecessaryExample);
        List<MonthNecessary> collect = monthNecessaries.stream().filter(s -> String.valueOf(s.getTypeSelf()).equals("0") || String.valueOf(s.getTypeSelf()).equals("1")).collect(Collectors.toList());
        if (collect.size() != monthNecessaries.size()) {
            return AjaxResult.error("必备项目中存在未填写项,请填写后提交");
        }
        //1.1.2 5级项目
        List<MonthSupplytaskDtl> monthSupplytaskDtls = monthSupplytaskDtlService.checkAllFill(monthSupplytask);
        if (monthSupplytaskDtls != null && monthSupplytaskDtls.size() > 0) {
            String num = monthSupplytaskDtls.get(0).getNum();
            return AjaxResult.error("指标编号为:" + num + "行数据未填写");
        }
        //1.2 验证总分、总得分、总扣分关系
        Boolean flag = monthSupplytaskDtlService.checkCanCommit(monthSupplytask);
        if (flag) {
            //------------2、更改单据状态，将单据状态从”未填报“变为”审核中“
            monthSupplytask = monthSupplytaskService.selectByPrimaryKey(id);
            //填报任务状态(0未填报/1分公司审核中/2分公司驳回调整/3责任部门审核中/4责任部门驳回调整/5审核完成)
            if (monthSupplytask.getTaskState().equals(MonthConstant.TASK_STATE_NOFILL)
                    ||monthSupplytask.getTaskState().equals(MonthConstant.TASK_STATE_ISREJECTED)) {
                //更改四级项目状态为“1” 分公司审核中
                monthSupplytask.setTaskState(MonthConstant.DTL_STATE_ISAUDITING);
                monthSupplytask.setCommitDate(new Date());
                monthSupplytask.setRejectReason("");
                monthSupplytaskService.updateByPrimaryKeySelective(monthSupplytask);

                //更改所有对应五级项目状态为“1” 分公司审核中
                //填报任务状态(0未填报/1分公司审核中/2分公司驳回调整/3责任部门审核中/4责任部门驳回调整/5审核完成/6完成分公司驳回项调整/7完成责任部门审核项调整)
                MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
                monthSupplytaskDtlExample.createCriteria().andFkTaskIdEqualTo(id);
                List<MonthSupplytaskDtl> monthSupplytaskDtls1 = monthSupplytaskDtlService.selectByExample(monthSupplytaskDtlExample);
                for (MonthSupplytaskDtl monthSupplytaskDtl : monthSupplytaskDtls1) {
                    monthSupplytaskDtl.setTaskState(MonthConstant.DTL_STATE_ISAUDITING);
                    monthSupplytaskDtl.setIsAuditedit(MonthConstant.NOT);
                    monthSupplytaskDtl.setIsSubauditedit(MonthConstant.NOT);
                    monthSupplytaskDtlService.updateByPrimaryKeySelective(monthSupplytaskDtl);
                }

                //更改所有对应月度必备项目状态为“1” 分公司审核中
                //任务状态(0未填报/1分公司审核中/2分公司驳回调整/3责任部门审核中/4责任部门驳回调整/5审核完成)
                MonthNecessaryExample monthNecessaryExample1 = new MonthNecessaryExample();
                monthNecessaryExample1.createCriteria().andFkTaskIdEqualTo(id);
                List<MonthNecessary> monthNecessaries1 = monthNecessaryService.selectByExample(monthNecessaryExample1);
                for (MonthNecessary monthNecessary : monthNecessaries1) {
                    monthNecessary.setTaskState(MonthConstant.DTL_STATE_ISAUDITING);
                    monthNecessary.setIsAuditedit(MonthConstant.NOT);
                    monthNecessary.setIsSubauditedit(MonthConstant.NOT);
                    monthNecessaryService.updateByPrimaryKeySelective(monthNecessary);
                }
                return AjaxResult.success();
            } else {
                return AjaxResult.error("该填报任务状态不是未填报或驳回调整状态，不允许提交");
            }
        } else {
            return AjaxResult.error("数据填报不规范，请核对数据");
        }
    }

    /**
     * list集合
     *
     * @param tablepar
     * @param
     * @return
     */
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/list4FillPlan/{evaluationId}")
    @ResponseBody
    public ResultTable list4FillPlan(@PathVariable("evaluationId") String evaluationId, Tablepar tablepar, MonthSupplytask monthSupplytask) {

        PageInfo<MonthSupplytask> page = monthSupplytaskService.list4FillPlan(evaluationId, tablepar, monthSupplytask);
        return pageTable(page.getList(), page.getTotal());
    }

    /**
     * 查看填报辅助文档
     */
    @ApiOperation(value = "查看填报辅助文档", notes = "查看填报辅助文档")
    @GetMapping("/viewhelp/{num}")
    public String viewhelp(@PathVariable("num") String num, ModelMap modelMap) {

        //查询操作步骤List
        InfoTargetStepExample infoTargetStepExample = new InfoTargetStepExample();
        infoTargetStepExample.createCriteria().andFkTargetIdEqualTo(num);
        List<InfoTargetStep> infoTargetSteps = infoTargetStepService.selectByExample(infoTargetStepExample);
        modelMap.put("infoTargetSteps", infoTargetSteps);
        //查询网址List
        InfoWeburlExample infoWeburlExample = new InfoWeburlExample();
        infoWeburlExample.createCriteria();
        List<InfoWeburl> infoWeburls = infoWeburlService.selectByExample(infoWeburlExample);
        modelMap.put("infoWeburls", infoWeburls);
        return prefix + "/viewhelp";
    }


    /**
     * 查看计算实时自评分跳转
     */
    @ApiOperation(value = "查看计算实时自评分跳转", notes = "查看计算实时自评分跳转")
    @GetMapping("/findSelfScore/{id}")
    public String findSelfScore(@PathVariable("id") String id, ModelMap modelMap) {
        //查询标签表头(一级+必备条件项目)
        modelMap.put("taskId", id);
        return prefix + "/viewselfscore";
    }

    /**
     * 查看实时扣分项跳转
     */
    @ApiOperation(value = "查看计算实时自评分跳转", notes = "查看计算实时自评分跳转")
    @GetMapping("/findDeduct/{id}")
    public String findDeduct(@PathVariable("id") String id, ModelMap modelMap) {
        //查询标签表头(一级+必备条件项目)
        modelMap.put("taskid", id);
        return prefix + "/viewdeduction";
    }

    /**
     * 分页 查询实时自评分结果（分页签统计）
     *
     * @param tablepar
     * @param
     * @return
     */
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/list4currentScore/{taskId}")
    @ResponseBody
    public ResultTable list4currentScore(@PathVariable("taskId") String taskId, Tablepar tablepar, MonthSupplytask monthSupplytask) {
        List<MonthResult> monthResultList = new ArrayList<>();
        //查询当前任务信息
        monthSupplytask = monthSupplytaskService.selectByPrimaryKey(taskId);
        //查询当前供电所信息
        InfoSupply infoSupply = infoSupplyService.selectByPrimaryKey(monthSupplytask.getSupplyId());
        //查询分项自评分得分、自评分总分并封装处理
        MonthSupplytaskDtl monthSupplytaskDtl = new MonthSupplytaskDtl();
        monthSupplytaskDtl.setFkTaskId(taskId);
        MonthResult monthResult = monthSupplytaskDtlService.findSelfScoreGroupbyTab(monthSupplytaskDtl);
        //查询必备项目填报情况并给出结论
        MonthNecessaryExample monthNecessaryExample = new MonthNecessaryExample();
        monthNecessaryExample.createCriteria().andFkTaskIdEqualTo(taskId).andTypeSelfIsNull();
        List<MonthNecessary> monthNecessaries = monthNecessaryService.selectByExample(monthNecessaryExample);
        if (monthNecessaries!=null && monthNecessaries.size()>0){
            monthResult.setIsNeccessary(MonthConstant.RESULT_ISAUDITING);
        }else {
            MonthNecessaryExample monthNecessaryExample1 = new MonthNecessaryExample();
            monthNecessaryExample1.createCriteria().andFkTaskIdEqualTo(taskId).andTypeSelfEqualTo(Integer.valueOf(MonthConstant.RESULT_FAIL));
            List<MonthNecessary> monthNecessaryList = monthNecessaryService.selectByExample(monthNecessaryExample1);
            if (monthNecessaryList!=null && monthNecessaryList.size()>0){
                monthResult.setIsNeccessary(MonthConstant.RESULT_FAIL);
            }else {
                monthResult.setIsNeccessary(MonthConstant.RESULT_OK);
            }
        }
        //结果数据封装
        monthResult.setTaskMonth(monthSupplytask.getTaskMonth());
        monthResult.setOrgnization(infoSupply.getOrganizationName());
        monthResult.setSupplyName(infoSupply.getName());
        monthResult.setStar(infoSupply.getStarrating());

        PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
        monthResultList.add(monthResult);
        PageInfo<MonthResult> page = new PageInfo<MonthResult>(monthResultList);

        return pageTable(page.getList(), page.getTotal());
    }

    /**
     * 查看提报结果跳转
     */
    @ApiOperation(value = "查看提报结果跳转", notes = "查看提报结果跳转")
    @GetMapping("/viewResult/{id}")
    public String viewResult(@PathVariable("id") String id, ModelMap modelMap) {
        //查询标签表头(一级+必备条件项目)
        List<InfoProject> infoProjects = infoProjectService.selectTabTitle();
        modelMap.put("tabTitleList", infoProjects);
        modelMap.put("taskId", id);
        return prefix + "/viewresult";
    }

    /**
     * 查看提报结果跳转
     */
    @ApiOperation(value = "查看提报结果跳转", notes = "查看提报结果跳转")
    @GetMapping("/viewDeduction/{id}")
    public String viewDeduction(@PathVariable("id") String id, ModelMap modelMap) {
        modelMap.put("taskid", id);
        return prefix + "/viewdeduction";
    }

    /**
     * 根据taskid查看对应供电所填报的扣分项
     */
    @ApiOperation(value = "根据taskid查看对应供电所填报的扣分项", notes = "根据taskid查看对应供电所填报的扣分项")
    @GetMapping("/list4supplydeduction/{id}")
    @ResponseBody
    public ResultTable list4supplydeduction(@PathVariable("id") String id,Tablepar tablepar) {
        PageInfo<MonthSupplytaskDtl> page = monthSupplytaskDtlService.list4supplydeduction(id,tablepar);
        return pageTable(page.getList(), page.getTotal());
    }

        /**
     * 查询月度分公司填报进度
     *
     * @param tablepar
     * @param
     * @return
     */
    @ApiOperation(value = "查询月度分公司填报进度", notes = "查询月度分公司填报进度")
    @GetMapping("/listbySub/{evaluationId}/{fkSubcompanyId}/{state}")
    @ResponseBody
    public ResultTable supplyList(@PathVariable("evaluationId") String evaluationId,@PathVariable("fkSubcompanyId") String fkSubcompanyId,@PathVariable("state") String state,Tablepar tablepar) {
        PageInfo<MonthSupplytask> page = monthSupplytaskService.supplyList(evaluationId,fkSubcompanyId,state,tablepar);
        return pageTable(page.getList(), page.getTotal());
    }

    /**
     * 月评价分析页面展示
     *
     * @param model
     * @return String
     * @author SQL
     */
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/viewana")
    @RequiresPermissions("gen:monthSupplytask:viewana")
    public String viewana(ModelMap model) {
        return prefixana + "/list";
    }

    /**
     * list集合--月度评价分析
     *
     * @param tablepar
     * @param
     * @return
     */
    //@Log(title = "月评价供电所填报任务表", action = "111")
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/list4ana")
    @RequiresPermissions("gen:monthSupplytask:list4ana")
    @ResponseBody
    public ResultTable list4ana(Tablepar tablepar, MonthSupplytask monthSupplytask) {
        PageInfo<MonthSupplytask> page = monthSupplytaskService.list(tablepar, monthSupplytask);
        return pageTable(page.getList(), page.getTotal());
    }

}
